<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>对应关系界面</title>
    <!--    引入css文件-->
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}" href="../static/layui/css/layui.css" type="text/css">
    <style>
        body {
            width: 94%;
            margin: 0 auto;
        }
        .layui-form-select {
            width: 240px;
            display: inline-block;
        }
        .add_group {
            display: flex;
            justify-content: space-between;
            /*margin-right: 20px;*/
            background-color: #fff;
            padding-bottom: 10px;
            border: 1px solid #eee;
            border-bottom: 0;
        }

        .layui-table-view {
            margin: 0 0 20px;
        }

        .add-relation, #upload_btn, #sort_by_user, #sort_by_stat {
            margin-left: 10px;
            margin-top: 10px;
        }
        #sort_by_stat {
            margin-right: 10px;
        }
    </style>
    <!--   引入js文件-->
    <script th:src="@{/jquery.min.js}" src="../static/jquery.min.js" type="text/javascript"></script>
    <script th:src="@{/layui/layui.js}" src="../static/layui/layui.js" type="text/javascript"></script>
</head>
<body>
<!--    编辑删除tool-->
<script type="text/html" id="barDemo">
<!--    <a class="layui-btn layui-btn-xs" lay-event="edit" style="color:#fff;">编辑</a>-->
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" style="color:#fff;">删除</a>
</script>
<div class="add_group">
    <div>
        <button type="button" class="layui-btn add-relation">添加对应关系</button>
        <button type="button" class="layui-btn" id="upload_btn">
            <i class="layui-icon">&#xe67c;</i> 批量上传
        </button>
    </div>

    <div>
        <button class="layui-btn layui-btn-primary" id="sort_by_user">按用户排序</button>
        <button class="layui-btn layui-btn-primary" id="sort_by_stat">按场站排序</button>

    </div>

</div>

<table id="relation_table"  lay-filter="relation"></table>
<!--            新增表单-->
<div id="add-main" style="display: none;">
    <form class="layui-form" id="add-form" action="">
        <div class="layui-form-item center">
            <label class="layui-form-label" style="width: 100px">用户名</label>
            <div class="layui-input-block">
                <select name="userid" lay-verify="required">
                    <option value="">请选择用户</option>
                    <option th:each="user : ${result.data.users}" th:value="${user.id}" th:text="${user.username}">用户名</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" style="width: 100px">场站名</label>
            <div class="layui-input-block">
                <select name="depotid" lay-verify="required">
                    <option value="">请选择场站</option>
                    <option th:each="stat : ${result.data.qrDepots}" th:value="${stat.id}" th:text="${stat.name}">场站名</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="save">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary" id="closeBtn">重置</button>
            </div>
        </div>
    </form>
</div>
</body>
<script th:inline="javascript">
    let relationData = [[${result.data.usersAndQrdepots}]]

    layui.use('table', function () {
        let table = layui.table;

        // 渲染用户列表
        table.render({
            elem: '#relation_table'
            ,limit: 9999
            ,data: relationData || []
            ,cols: [
                [
                    {field: 'userid', title: '用户id', width: 120, align: 'center', style:'background-color:#FFFFFF'}
                    ,{field: 'username', title: '用户名', minWidth:160, align: 'center'}
                    ,{field: 'phone',title: '手机号',minWidth:160, align: 'center'}
                    ,{field: 'depotid', title: '场站id', width: 120, align: 'center'}
                    ,{field: 'name', title: '场站名称', minWidth:160, align: 'center'}
                    ,{ fixed: 'right', title: '操作', width: 200, align: 'center', toolbar: '#barDemo' }
                ]
            ]
            ,done : function(res, curr, count) {
                merge(res);
            }
        })

        //监听工具条
        table.on('tool(relation)', function (obj) {
            let data = obj.data;
            if (obj.event === 'detail') {
                layer.msg('ID：' + data.id + ' 的查看操作'); // 暂时不增加查看功能
            }
            else if (obj.event === 'del') {
                layer.confirm('确定要删除（'+ data.username+ ' — ' + data.name+'）这条对应关系么', function (index) {
                    $.ajax({
                        type: "GET",
                        url: '/qruseranddepot/delete',
                        contentType:'application/json',
                        // data: JSON.stringify({ id: data.id }),
                        data: {id:data.id},
                        success: function (res) {
                            if (res.code != 0) {
                                layer.alert(res.msg)
                            } else {
                                layer.alert('删除成功')
                                // layer.alert(res.msg)
                                obj.del();
                                layer.close(index);
                            }
                        }
                    })
                });
            }
        });
    });
    // 上传excel文件
    layui.use('upload', function(){
        let upload = layui.upload;
        //执行实例
        let uploadInst = upload.render({
            elem: '#upload_btn' //绑定元素
            ,url: '/qruseranddepot/uploadFile' //上传接口
            ,accept: 'file' //允许上传的文件类型
            ,exts: 'csv' //只允许上传csv文件
            // ,auto: false //是否自动上传
            // ,bindAction: '#btn' // 指向一个按钮触发上传，一般配合 auto: false 来使用。值为选择器或DOM对象
            ,done: function(res){
                //上传完毕回调
                // 刷新页面
                if(res.code == 0) {
                    layer.alert('批量上传成功', function (){
                        parent.location.reload();
                    })
                } else {
                    layer.alert(res.msg)
                }
            }
            ,error: function(){
                //请求异常回调
            }
        });
    });

    //排序
    $('#sort_by_stat').on('click', function () {
        location.href="/qruseranddepot/list?type=0"
        // location.reload()
    })
    $('#sort_by_user').on('click', function () {
        location.href="/qruseranddepot/list?type=1"
    })

    //  新增事件
    $('.add-relation').on('click', function () {
        let type = $(this).data('type'); //页面层
        layer.open({
            type: 1, skin: 'layui-layer-rim', //加上边框
            area: ['430px', '300px'], //宽高
            content: $("#add-main"),
            title: ['新增对应关系','margin-bottom:15px']
        });
    });

    // 注册弹层的表格
    layui.use(['layer', 'form'], function () {
        let layer = layui.layer, $ = layui.jquery, form = layui.form;
        //提交监听事件
        form.on('submit(save)', function (data) {
            params = data.field;
            // 判断当前对应关系是否已存在
            let curData = relationData.filter(item =>
                item.userid == params.userid
            )
            let res = curData.find(item => item.depotid == params.depotid)
            if(res) {
                layer.alert('当前对应关系已存在')
                return false
            } else {
                submit($, params);
                return false;
            }

        })



    })

    //增加提交
    function submit ($, params) {
        $.ajax({
            type: "post",
            url: '/qruseranddepot/add',
            data: JSON.stringify(params),
            contentType:'application/json',
            success: function (res) {
                if (res.code != 0) {
                    alert(res.msg)
                } else {
                    layer.msg(res.msg, { icon: 0, time: 500 },
                        function () {
                            parent.location.reload();
                            // 页面刷新
                            return false
                        })
                }
            }
        });
    }

    //合并单元格
    function merge (res) {
        let data = res.data;
        let mergeIndex = 0;//定位需要添加合并属性的行数
        let mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
        // let columsName = ['id','name'];//需要合并的列名称
        let str = location.href
        let type = str.charAt(str.length - 1)
        let columsName = type == 1 ? ['userid', 'username', 'phone'] : ['depotid', 'name'];//需要合并的列名称
        let columsIndex =  type == 1 ? [0, 1,2] : [3, 4];//需要合并的列索引值

        for (let k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
            let trArr = $(".layui-table-body>.layui-table").find("tr");//所有行
            for (let i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                let tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                let tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列

                if (data[i][columsName[k]] === data[i - 1][columsName[k]]) { //后一行的值与前一行的值做比较，相同就需要合并
                    mark += 1;
                    tdPreArr.each(function () {//相同列的第一列增加rowspan属性
                        $(this).attr("rowspan", mark);
                    });
                    tdCurArr.each(function () {//当前行隐藏
                        $(this).css("display", "none");
                    });
                } else {
                    mergeIndex = i;
                    mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                }
            }
            mergeIndex = 0;
            mark = 1;
        }
    }


</script>
</html>